<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class Message extends Model
{
    protected $fillable = [
        'type', 'notifiable_type','data'
    ];

    protected $table = 'notifications';

    public static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            if($model->notifiable_id == 0){
                $user_id = DB::table('users')->pluck('id');
                $data = [];
                foreach($user_id as $v){
                    $data[] = [
                        'type' => $model->type,
                        'notifiable_type' => $model->notifiable_type,
                        'notifiable_id' => $v,
                        'data' => $model->data,
                    ];
                }
                DB::table('notifications')->insert($data);
                return redirect('/admin/messages');
            }


        });
    }


    public function user()
    {
        return $this->belongsTo(User::class,'notifiable_id');
    }



}
